from math import nan
import akshare as ak
import pandas as pd
from datetime import datetime
import time

from config.database import engine

# 从akshare获取股票的基本信息


def fetch_all_a_stocks():
    """获取所有A股股票列表"""
    try:
        df = ak.stock_info_a_code_name()
        print(f"获取到 {len(df)} 只A股股票")
        return df
    except Exception as e:
        print(f"获取股票列表失败: {e}")
        return pd.DataFrame()

# 保存股票基本信息


def save_stock_basic(stock_list):
    """保存股票基本信息"""
    try:
        stock_list.to_sql('stock_basic', engine,
                          if_exists='append', index=False)
        print("股票基本信息保存成功")
    except Exception as e:
        print(f"保存股票基本信息失败: {e}")

# 获取股票基本信息


def get_stock_basic():
    """获取股票基本信息"""
    try:
        sql = 'select symbol, name FROM mbnstock.stock_basic;'
        stock_list = pd.read_sql(sql, engine)
        print("股票基本信息获取成功")
        return stock_list
    except Exception as e:
        print(f"获取股票基本信息失败: {e}")
        return pd.DataFrame()

# 获取股票交易信息


def get_stock_data(symbol: str, period: str = 'daily'):
    """获取股票交易信息"""
    try:
        sql = f'select symbol, trade_date, open, close, high, low FROM mbnstock.stock_{period}'
        if symbol:
            sql = sql + f' where symbol = {symbol}'
        data = pd.read_sql(sql, engine)
        print("股票基本信息获取成功")
        return data
    except Exception as e:
        print(f"获取股票基本信息失败: {e}")
        return pd.DataFrame()

# 获取未同步的股票


def get_stock_not_synchr(period='daily'):
    """获取未同步股票信息"""
    try:
        table_name = 'stock_' + period
        sql = 'select DISTINCT symbol  FROM stock_basic sb where sb.symbol not in(select DISTINCT symbol  FROM ' \
            + table_name + ');'
        stock_list = pd.read_sql(sql, engine)
        print("未同步股票信息获取成功")
        return stock_list
    except Exception as e:
        print(f"获取未同步股票信息失败: {e}")
        return pd.DataFrame()

# 从akshare获取股票日线数据


def fetch_daily_data(symbol, start_date='20100101', period='daily'):
    """获取股票日线数据"""
    try:
        end_date = datetime.now().strftime('%Y%m%d')
        df = ak.stock_zh_a_hist(symbol=symbol, period=period,
                                start_date=start_date, end_date=end_date, adjust="qfq")

        if df.empty:
            return pd.DataFrame()

        df = df.reset_index()
        return df
    except Exception as e:
        print(f"获取 {symbol} 日线数据失败: {e}")
        return pd.DataFrame()

#


def rename_data(old_data: pd.DataFrame):
    '''
        重名命df, 从akshare获得的数据列名是中文，转化成英文
    '''
    try:
        old_data.drop('index', axis=1, inplace=True)
        old_data.rename(columns={
            "日期": "trade_date",
            "股票代码": "symbol",
            "开盘": "open",
            "收盘": "close",
            "最高": "high",
            "最低": "low",
            "成交量": "vol",
            "成交额": "amount",
            "振幅": "amplitude",
            "涨跌幅": "pct_chg",
            "涨跌额": "chg",
            "换手率": "turn"
        }, inplace=True
        )
    except Exception as e:
        print(f"调整数据失败: {e}")


def save_to_database(data, table_name):
    """保存数据到数据库"""
    if data.empty:
        return

    try:
        data.to_sql(table_name, engine, if_exists='append', index=False)
        print(f"成功保存 {len(data)} 条数据到 {table_name} 表")
    except Exception as e:
        print(f"保存数据到 {table_name} 失败: {e}")
